題目
Repeated String
舉例輸入
aba
10
舉例輸出
7
舉例輸入
a
1000000000000
舉例輸出
1000000000000
解析
這題那時候寫了很久
因為我會錯意了
題旨只要求
"a"這個字母經過字串與重複後出現了幾次
而我寫成第一個字母經過重複後出現了幾次
....
先看第一個錯誤解(靈活解??)
function repeatedString(s, n) {
//結果次數
let result = 0;
//目標字母
let letterIsAt = (n % s.length) - 1
let letter = s[letterIsAt < 0 ? 0 : letterIsAt];
//計算完整重複幾次
let loopCount = Math.floor(n / s.length);
//計算最後不完整時到底幾字元
let lastCherAt = (n - (loopCount * s.length)) - 1
//計算這個字母在原字串出現幾次、不完整字串出現幾次
let strTotal = 0;
let strPart = 0;
s.split('').forEach((str, index) => {
if (str == letter) {
strTotal += 1;
if (index <= lastCherAt) {
strPart += 1
}
}
})
result = (strTotal * loopCount) + strPart
return result;
}
然而如果題目只是要"a"
那麼我們只要把關鍵字元改掉即可
function repeatedString(s, n) {
//結果次數
let result = 0;
//目標字母
let letterIsAt = (n % s.length) - 1
let letter = 'a';
//計算完整重複幾次
let loopCount = Math.floor(n / s.length);
//計算最後不完整時到底幾字元
let lastCherAt = (n - (loopCount * s.length)) - 1
//計算這個字母在原字串出現幾次、不完整字串出現幾次
let strTotal = 0;
let strPart = 0;
s.split('').forEach((str, index) => {
if (str == letter) {
strTotal += 1;
if (index <= lastCherAt) {
strPart += 1
}
}
})
result = (strTotal * loopCount) + strPart
return result;
}
.....真是浪費生命呀(笑)